package com.example.learn_spring_boot3.service.impl;

import com.example.learn_spring_boot3.service.TestMysqlService;
import com.example.learn_spring_boot3.utils.ResponseData;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Service
public class TestMysqlServiceImpl implements TestMysqlService {
    // DataSource(即数据库、数据源)
    @Resource
    DataSource dataSource;

    // JdbcTemplate 里面封装了一些对数据库操作的方法
    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public ResponseEntity<ResponseData> queryUserList() {
        Class<? extends DataSource> aClass = dataSource.getClass();
        System.out.println("使用的数据源: " + aClass);

        String sql = "SELECT * FROM user";
        List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql);
        ResponseData<Object> success = ResponseData.success(dataList);
        return ResponseEntity.ok(success);
    }

    @Override
    public ResponseEntity<ResponseData> addUser() {
        String sql = "INSERT INTO learn_spring_boot3.user(name, age, sex, password) VALUES ('王五', 18, 1, '000000')";
        jdbcTemplate.update(sql);
        ResponseData<Object> success = ResponseData.success(null);
        return ResponseEntity.ok(success);
    }

    @Override
    public ResponseEntity<ResponseData> deleteUser(int id) {
        // TODO 参数校验...
        ResponseData<Object> success = ResponseData.success(null);

        Object[] objects = new Object[1];
        objects[0] = id;

        // Object[] objects = new Object[]{id};

        String sql = "DELETE FROM learn_spring_boot3.user WHERE id=?";
        jdbcTemplate.update(sql, objects);
        return ResponseEntity.ok(success);
    }
}
